package com.sl.au.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.runtime.ProcessInstance;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.entity.Attachment;
import com.sl.au.entity.AuditRoot;
import com.sl.au.entity.Contract;
import com.sl.au.entity.ContractInfo;
import com.sl.au.entity.ContractPart;
import com.sl.au.entity.ContractPump;
import com.sl.au.entity.ContractRepair;
import com.sl.au.entity.ContractVo;
import com.sl.au.entity.DetailRelevance;
import com.sl.au.entity.DivideScale;
import com.sl.au.entity.Option;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.repository.ContractInfoRepository;
import com.sl.au.repository.ContractPartRepository;
import com.sl.au.repository.ContractPumpRepository;
import com.sl.au.repository.ContractRepairRepository;
import com.sl.au.repository.ContractRepository;
import com.sl.au.repository.DetailRelevanceRepository;
import com.sl.au.repository.DeviceRepository;
import com.sl.au.repository.DivideScaleRepository;
import com.sl.au.repository.QuoteDeviceRepository;
import com.sl.au.repository.QuoteReplacementRepository;
import com.sl.au.repository.ReplacementDeviceRepository;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.AuditNodeService;
import com.sl.au.service.ContractQueryService;
import com.sl.au.service.ContractService;
import com.sl.au.service.ExcelService;
import com.sl.au.service.OptionService;

/**
 * 合同管理接口
 * 
 * @author XH
 *
 */
@Service("ContractQueryService")
@Transactional
public class ContractQueryServiceImpl extends BaseServiceImpl implements ContractQueryService {

	@Autowired
	ContractRepository contractRepository;
	
	@Autowired
	ContractInfoRepository contractInfoRepository;

	@Autowired
	DivideScaleRepository divideScaleRepository;

	@Autowired
	ContractPartRepository contractPartRepository;

	@Autowired
	ContractPumpRepository contractPumpRepository;

	@Autowired
	ContractRepairRepository contractRepairRepository;

	@Autowired
	QuoteDeviceRepository quoteDeviceRepository;

	@Autowired
	QuoteReplacementRepository quoteReplacementRepository;

	@Autowired
	DetailRelevanceRepository detailRelevanceRepository;

	@Autowired
	ReplacementDeviceRepository replacementDeviceRepository;

	@Autowired
	DeviceRepository deviceRepository;

	@Autowired
	ExcelService excelService;
	
	@Autowired
	AuditNodeService auditNodeService;
	
	@Autowired
	AttachmentService attachmentService;
	
	@Autowired
	OptionService optionService;

	public ContractRepository getRepository() {
		return this.contractRepository;
	}
	
	public ContractInfoRepository getContractInfoRepository() {
		return this.contractInfoRepository;
	}

	public DivideScaleRepository getRepository1() {
		return this.divideScaleRepository;
	}

	public ContractPartRepository getRepository2() {
		return this.contractPartRepository;
	}

	public ContractPumpRepository getRepository3() {
		return this.contractPumpRepository;
	}

	public ContractRepairRepository getRepository4() {
		return this.contractRepairRepository;
	}

	public QuoteDeviceRepository getRepository5() {
		return this.quoteDeviceRepository;
	}

	public DetailRelevanceRepository getRepository6() {
		return this.detailRelevanceRepository;
	}

	public ReplacementDeviceRepository getRepository7() {
		return this.replacementDeviceRepository;
	}

	public DeviceRepository getRepository8() {
		return this.deviceRepository;
	}

	public QuoteReplacementRepository getRepository9() {
		return this.quoteReplacementRepository;
	}
	
	@Override
	public List<ContractInfo> getContractInfos(int start, int length, Map<String, Object> condition, String orderName, String dir) {
		Page<ContractInfo> pages = null;
		String dataFilter = (String)condition.get("dataFilter");
		String superior = (String)condition.get("superior");
		String areaName = (String)condition.get("areaName");
		String userId = (String)condition.get("userId");
		String supplierCode = (String)condition.get("supplierCode");
		String contractType = (String)condition.get("contractType");
		String minSumStr = (String)condition.get("minSumStr");
		String maxSumStr = (String)condition.get("maxSumStr");
		String startDateStr = (String)condition.get("startDateStr");
		String endDateStr = (String)condition.get("endDateStr");
		String startDate1Str = (String)condition.get("startDate1Str");
		String endDate1Str = (String)condition.get("endDate1Str");
		String outDateStr = (String)condition.get("outDateStr");
		String orderUnit = (String)condition.get("orderUnit");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date minDate = null;
		try {
			minDate = simpleDateFormat.parse("1970-01-01");
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Date maxDate = null;
		try {
			maxDate = simpleDateFormat.parse("2070-01-01");
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (userId == null) {userId = "";}
		if (superior == null) {superior = "";}
		if (areaName == null) {areaName = "";}
		if (dataFilter == null) {dataFilter = "";}
		if (supplierCode == null) {supplierCode = "";}
		if (contractType == null) {contractType = "";}
		float minSum = 0;
		if (minSumStr != null && minSumStr != "") {
			minSum = Float.parseFloat(minSumStr);
		}
		float maxSum = (float) 10000000000.0;
		if (maxSumStr != null && maxSumStr != "") {
			maxSum = Float.parseFloat(maxSumStr);
		}
		Date startDate = null;
		if (startDateStr == null || startDateStr =="") {
			startDate = minDate;
		}else{
			try {
				startDate = simpleDateFormat.parse(startDateStr);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Date endDate = null;
		if (endDateStr == null || endDateStr =="") {
			endDate = maxDate;
		}else{
			try {
				endDate = simpleDateFormat.parse(endDateStr);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Date startDate1 = null;
		if (startDate1Str == null || startDate1Str =="") {
			startDate1 = minDate;
		}else{
			try {
				startDate1 = simpleDateFormat.parse(startDate1Str);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Date endDate1 = null;
		if (endDate1Str == null || endDate1Str =="") {
			endDate1 = maxDate;
		}else{
			try {
				endDate1 = simpleDateFormat.parse(endDate1Str);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Date startDate2 = null;
		Date endDate2 = null;
		if (outDateStr == null || outDateStr =="" || outDateStr.equals("all")){
			startDate2 = minDate;
			endDate2 = maxDate;
		}else{
			if (outDateStr.equals("out")){
				startDate2 = minDate;
				endDate2 = new Date();
			}else{
				String[] params = outDateStr.split(",");// params[0]是年份，params[1]是月份
				int year = Integer.parseInt(params[0]);
				int month = Integer.parseInt(params[1]);
				int day = 31;
				switch (month) {
				case 4:	case 6:	case 9:	case 11:			
					day = 30;
					break;
				case 2:			
					if (year%4==0){
						if (year%100==0 && year%400!=0){
							day = 28;
						}else{
							day = 29;
						}
					}else{
						day = 28;
					}
					break;
				}
				try {
					startDate2 = simpleDateFormat.parse(year+"-"+month+"-01");
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					endDate2 = simpleDateFormat.parse(year+"-"+month+"-"+day);
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		if (orderUnit == null) {orderUnit = "";}
		supplierCode = supplierCode.replaceAll("\\s+", "");
		orderUnit = orderUnit.replaceAll("\\s+", "");
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		if(dataFilter.equals("所有")){
			pages = contractRepository.getContractInfos(supplierCode, contractType, minSum, maxSum, 
					startDate, endDate, startDate1, endDate1, startDate2, endDate2, orderUnit, pageable);
		}else if(dataFilter.equals("本部门")){
			pages = contractRepository.getContractInfos(supplierCode, contractType, minSum, maxSum, 
					startDate, endDate, startDate1, endDate1, startDate2, endDate2, orderUnit, superior, pageable);
		}else if(dataFilter.equals("本片区")){
			pages = contractRepository.getContractInfos(supplierCode, contractType, minSum, maxSum, 
					startDate, endDate, startDate1, endDate1, startDate2, endDate2, orderUnit, superior, areaName, pageable);
		}else{
			pages = contractRepository.getContractInfosByUser(supplierCode, contractType, minSum, maxSum, 
					startDate, endDate, startDate1, endDate1, startDate2, endDate2, orderUnit, userId, pageable);
		}
		return pages.getContent();
	}
	
	@Override
	public long getContractInfosCount(Map<String, Object> condition) {
		String dataFilter = (String)condition.get("dataFilter");
		String superior = (String)condition.get("superior");
		String areaName = (String)condition.get("areaName");
		String userId = (String)condition.get("userId");
		String supplierCode = (String)condition.get("supplierCode");
		String contractType = (String)condition.get("contractType");
		String minSumStr = (String)condition.get("minSumStr");
		String maxSumStr = (String)condition.get("maxSumStr");
		String startDateStr = (String)condition.get("startDateStr");
		String endDateStr = (String)condition.get("endDateStr");
		String startDate1Str = (String)condition.get("startDate1Str");
		String endDate1Str = (String)condition.get("endDate1Str");
		String outDateStr = (String)condition.get("outDateStr");
		String orderUnit = (String)condition.get("orderUnit");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date minDate = null;
		try {
			minDate = simpleDateFormat.parse("1970-01-01");
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Date maxDate = null;
		try {
			maxDate = simpleDateFormat.parse("2070-01-01");
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (userId == null) {userId = "";}
		if (superior == null) {superior = "";}
		if (areaName == null) {areaName = "";}
		if (dataFilter == null) {dataFilter = "";}
		if (supplierCode == null) {supplierCode = "";}
		if (contractType == null) {contractType = "";}
		float minSum = 0;
		if (minSumStr != null && minSumStr != "") {
			minSum = Float.parseFloat(minSumStr);
		}
		float maxSum = (float) 10000000000.0;
		if (maxSumStr != null && maxSumStr != "") {
			maxSum = Float.parseFloat(maxSumStr);
		}
		Date startDate = null;
		if (startDateStr == null || startDateStr =="") {
			startDate = minDate;
		}else{
			try {
				startDate = simpleDateFormat.parse(startDateStr);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Date endDate = null;
		if (endDateStr == null || endDateStr =="") {
			endDate = maxDate;
		}else{
			try {
				endDate = simpleDateFormat.parse(endDateStr);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Date startDate1 = null;
		if (startDate1Str == null || startDate1Str =="") {
			startDate1 = minDate;
		}else{
			try {
				startDate1 = simpleDateFormat.parse(startDate1Str);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Date endDate1 = null;
		if (endDate1Str == null || endDate1Str =="") {
			endDate1 = maxDate;
		}else{
			try {
				endDate1 = simpleDateFormat.parse(endDate1Str);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Date startDate2 = null;
		Date endDate2 = null;
		if (outDateStr == null || outDateStr =="" || outDateStr.equals("all")){
			startDate2 = minDate;
			endDate2 = maxDate;
		}else{
			if (outDateStr.equals("out")){
				startDate2 = minDate;
				endDate2 = new Date();
			}else{
				String[] params = outDateStr.split(",");// params[0]是年份，params[1]是月份
				int year = Integer.parseInt(params[0]);
				int month = Integer.parseInt(params[1]);
				int day = 31;
				switch (month) {
				case 4:	case 6:	case 9:	case 11:			
					day = 30;
					break;
				case 2:			
					if (year%4==0){
						if (year%100==0 && year%400!=0){
							day = 28;
						}else{
							day = 29;
						}
					}else{
						day = 28;
					}
					break;
				}
				try {
					startDate2 = simpleDateFormat.parse(year+"-"+month+"-01");
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					endDate2 = simpleDateFormat.parse(year+"-"+month+"-"+day);
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		if (orderUnit == null) {orderUnit = "";}
		supplierCode = supplierCode.replaceAll("\\s+", "");
		orderUnit = orderUnit.replaceAll("\\s+", "");
		if(dataFilter.equals("所有")){
			return this.contractRepository.getContractInfoCount(supplierCode, contractType, minSum, maxSum, 
					startDate, endDate, startDate1, endDate1, startDate2, endDate2, orderUnit);
		}else if(dataFilter.equals("本部门")){
			return this.contractRepository.getContractInfoCount(supplierCode, contractType, minSum, maxSum, 
					startDate, endDate, startDate1, endDate1, startDate2, endDate2, orderUnit, superior);
		}else if(dataFilter.equals("本片区")){
			return this.contractRepository.getContractInfoCount(supplierCode, contractType, minSum, maxSum, 
					startDate, endDate, startDate1, endDate1, startDate2, endDate2, orderUnit, superior, areaName);
		}else{
			return this.contractRepository.getContractInfoByUserCount(supplierCode, contractType, minSum, maxSum, 
					startDate, endDate, startDate1, endDate1, startDate2, endDate2, orderUnit, userId);
		}
	}

	@Override
	public List<Option> getOutDateLists() {
		List<Option> outDateLists = new ArrayList<Option>();
		Calendar calendar=Calendar.getInstance();
		//获得当前时间的月份，月份从0开始所以结果要加1
		int month=calendar.get(Calendar.MONTH)+1;
		int year=calendar.get(Calendar.YEAR);
		Option outDateListFirst = new Option();
		outDateListFirst.setTitle("所有合同");
		outDateListFirst.setValue("all");
		outDateLists.add(outDateListFirst);
		int count = 6;
		List<Option> outDateSelects =  optionService.getRepository().
										findByGroupAndTitle("合同综合查询", "超期合同");
		if (outDateSelects.size()>0){
			if (outDateSelects.get(0).getValue()!=null
					&&!outDateSelects.get(0).getValue().equals("")){
				try {
					count = Integer.parseInt(outDateSelects.get(0).getValue());
				} catch (NumberFormatException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		for(int n = count; n>0; n--){
			Option outDateList = new Option();
			String title = year+"年"+month+"月交货合同";
			String value = year+","+month;
			if (month==1){
				year -= 1;
				month = 12;
			}else{
				month -= 1;
			}
			outDateList.setTitle(title);
			outDateList.setValue(value);
			outDateLists.add(outDateList);
		}
		Option outDateListEnd = new Option();
		outDateListEnd.setTitle("已逾期合同");
		outDateListEnd.setValue("out");
		outDateLists.add(outDateListEnd);
		return outDateLists;
	}
	

}
